package com.example.pagingdemo;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.PageKeyedDataSource;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.pagingdemo.databinding.ActivityDoctorBinding;
import com.example.pagingdemo.model.DoctorVo;
import com.example.pagingdemo.paging.MutablePageKeyedDataSource;
import com.example.pagingdemo.paging.doctor.DoctorAdapter;
import com.example.pagingdemo.paging.doctor.DoctorViewModel;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.List;

/**
 * @author: tuyrt7 on 2020/10/27.
 */
public class DoctorListActivity extends AppCompatActivity implements OnRefreshListener, OnLoadMoreListener {

    private ActivityDoctorBinding binding;
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;
    private DoctorViewModel doctorViewModel;
    private DoctorAdapter doctorAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_doctor);

        recyclerView = binding.recyclerView;
        refreshLayout = binding.refreshLayout;

        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(null);

        doctorAdapter = new DoctorAdapter();
        recyclerView.setAdapter(doctorAdapter);

        doctorViewModel = new ViewModelProvider(this).get(DoctorViewModel.class);
        doctorViewModel.getPagedData().observe(this, new Observer<PagedList<DoctorVo.DocArrBean>>() {
            @Override
            public void onChanged(PagedList<DoctorVo.DocArrBean> docArrBeans) {
                Log.i("aaaaa", "PagedData onChanged: "+docArrBeans.size());
                submitList(docArrBeans);
            }
        });

        doctorViewModel.getBoundaryPageData().observe(this,hasData -> finishRefresh(hasData));
    }

    private void submitList(PagedList<DoctorVo.DocArrBean> docArrBeans) {
        if (docArrBeans.size() > 0) {
            doctorAdapter.submitList(docArrBeans);
        }
        finishRefresh(docArrBeans.size() > 0);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        Log.i("aaaaa", "============onRefresh===============: ");
        doctorViewModel.getDataSource().invalidate();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        Log.i("aaaaa", "============onLoadMore===============: ");
        //若列表数据为空，则不触发上拉加载更多数据
        final PagedList<DoctorVo.DocArrBean> currentList = doctorAdapter.getCurrentList();
        if (currentList == null || currentList.size() <= 0) {
            finishRefresh(false);
            return;
        }


        //需要注意这里，在PaingProViewModel中自实现loadAfter方法，实现请求分页数据的逻辑
        doctorViewModel.loadAfter(doctorViewModel.getPageIndex(),new PageKeyedDataSource.LoadCallback<Integer, DoctorVo.DocArrBean>(){

            @Override
            public void onResult(@NonNull List<DoctorVo.DocArrBean> data, @Nullable Integer adjacentPageKey) {
                PagedList.Config config = currentList.getConfig();
                if (data != null && data.size() > 0) {
                    //这里 咱们手动接管 分页数据加载的时候 使用MutableItemKeyedDataSource也是可以的。
                    //由于当且仅当 paging不再帮我们分页的时候，我们才会接管。所以 就不需要ViewModel中创建的DataSource继续工作了，所以使用新的DataSource对象，这里是MutablePageKeyedDataSource
                    MutablePageKeyedDataSource dataSource = new MutablePageKeyedDataSource();

                    //这里要把列表上已经显示的先添加到dataSource.data中
                    //而后把本次分页回来的数据再添加到dataSource.data中
                    dataSource.data.addAll(currentList);
                    dataSource.data.addAll(data);

                    PagedList pagedList = dataSource.buildNewPagedList(config);
                    submitList(pagedList);
                }
            }
        });
    }

    private void finishRefresh(boolean hasData) {
        Log.d("TAG", "finishRefresh: " +hasData);
        PagedList<DoctorVo.DocArrBean> currentList = doctorAdapter.getCurrentList();
        hasData = hasData || currentList != null && currentList.size() > 0;
        RefreshState state = refreshLayout.getState();
        if (state.isFooter && state.isOpening) {
            refreshLayout.finishLoadMore();
        } else if (state.isHeader && state.isOpening) {
            refreshLayout.finishRefresh();
        }
//
//        if (hasData) {
//            emptyView.setVisibility(View.GONE);
//        } else {
//            emptyView.setVisibility(View.VISIBLE);
//        }
    }
}
